#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import requests
import json
import sys

class WeChatSender:
    def __init__(self):
        self._load_config()
        
    def _load_config(self):
        """加载基础配置"""
        BASE_CONFIG = os.environ.get("QYWX_BASE_CONFIG")
        if not BASE_CONFIG:
            print("❌ 环境变量 QYWX_BASE_CONFIG 未设置!")
            sys.exit(1)
            
        base_parts = self._parse_config(BASE_CONFIG)
        if len(base_parts) < 4:
            print("❌ 基础配置格式错误：必须包含4个参数（企业ID#Secret#AgentId#代理地址）")
            print("示例: wxcorpid#secret#agentid#https://proxy.example.com")
            sys.exit(1)
            
        self.CORP_ID = base_parts[0]
        self.SECRET = base_parts[1]
        self.AGENT_ID = base_parts[2]
        self.PROXY_URL = base_parts[3]
        
    def _parse_config(self, config_str):
        """解析配置字符串"""
        parts = config_str.split('#')
        return [part.strip() for part in parts if part.strip()]
        
    def get_access_token(self):
        """获取企业微信API的访问令牌"""
        url = f"{self.PROXY_URL}/cgi-bin/gettoken?corpid={self.CORP_ID}&corpsecret={self.SECRET}"
        try:
            response = requests.get(url, timeout=10)
            result = response.json()
            if result.get("errcode") == 0:
                return result["access_token"]
            else:
                print(f"❌ 获取Access Token失败: {result.get('errmsg')}")
                print(f"请求URL: {url}")
                return None
        except Exception as e:
            print(f"🚨 请求异常: {str(e)}")
            return None
            
    def send_message(self, to_user, message_content, media_id=""):
        """发送消息到企业微信"""
        access_token = self.get_access_token()
        if not access_token:
            print("❌ 无法获取Access Token，消息发送终止")
            return False
            
        url = f"{self.PROXY_URL}/cgi-bin/message/send?access_token={access_token}"
        
        # 使用文本消息类型
        msg_type = "text"
        content = {"content": message_content}
        
        payload = {
            "touser": to_user,
            "msgtype": msg_type,
            "agentid": int(self.AGENT_ID),
            msg_type: content
        }
        
        # 添加素材ID（如果提供）
        if media_id:
            payload["media_id"] = media_id
        
        headers = {'Content-Type': 'application/json'}
        
        try:
            response = requests.post(url, data=json.dumps(payload), headers=headers, timeout=15)
            result = response.json()
            
            if result.get("errcode") == 0:
                print(f"✅ 消息发送成功! 接收人: {to_user}")
                print(f"代理地址: {self.PROXY_URL}")
                print(f"消息ID: {result.get('msgid')}")
                return True
            else:
                print(f"❌ 消息发送失败! 接收人: {to_user}")
                print(f"错误代码: {result.get('errcode')}")
                print(f"错误信息: {result.get('errmsg')}")
                
                # 错误代码特定建议
                if result.get('errcode') == 60020:
                    print("\n⚠️ 解决方案:")
                    print(f"1. 将代理服务器IP添加到企业可信IP: {self.PROXY_URL.split('//')[1].split('/')[0]}")
                    print("2. 企业微信后台 > 应用管理 > 目标应用 > 安全设置 > 企业可信IP")
                
                print("\n🔧 通用排查:")
                print(f"1. 检查代理地址是否可达: {self.PROXY_URL}")
                print(f"2. 确认接收人 '{to_user}' 在应用可见范围内")
                print(f"3. 确保应用Secret正确: {self.SECRET[:4]}...{self.SECRET[-4:]}")
                return False
                
        except Exception as e:
            print(f"🔴 发送请求失败: {str(e)}")
            return False

# 提供全局实例
wechat_sender = WeChatSender()

if __name__ == "__main__":
    # 命令行模式兼容性
    MESSAGE_CONFIG = os.environ.get("QYWX_MESSAGE_CONFIG", "")
    if not MESSAGE_CONFIG:
        print("❌ 环境变量 QYWX_MESSAGE_CONFIG 未设置!")
        sys.exit(1)
        
    parts = [p.strip() for p in MESSAGE_CONFIG.split('#') if p.strip()]
    if len(parts) < 2:
        print("❌ 消息配置格式错误：至少需要2个参数（接收人ID#消息内容）")
        sys.exit(1)
        
    to_user = parts[0]
    message_content = parts[1]
    media_id = parts[2] if len(parts) > 2 else ""
    
    wechat_sender.send_message(to_user, message_content, media_id)